package com.lagou.service.impl;

import cn.hutool.core.util.IdUtil;
import com.lagou.dao.TokenDao;
import com.lagou.dao.UserDao;
import com.lagou.model.Result;
import com.lagou.model.ResultStatus;
import com.lagou.pojo.User;
import com.lagou.service.IAuthCodeService;
import com.lagou.service.IUserService;
import com.lagou.pojo.Token;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.Objects;
import java.util.UUID;

@Service
@Component
@Transactional
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserDao userDao;

    @Autowired
    private TokenDao tokenDao;

    @Reference
    private IAuthCodeService authCodeService;

    @Override
    public Result register(String email, String password, String code) {

        if (isRegistered(email)) {
            Result.build(ResultStatus.ERROR_SYSTEM, "该邮箱已注册！");
        }
        Result authResult = authCodeService.validateAuthCode(email, code);
        if (Result.isOK(authResult) ) {
            User user = new User();
            user.setEmail(email);
            user.setPassword(password);
            user.setCreateTime(new Date());
            user.setLogintime(new Date());
            userDao.save(user);

            return Result.ok(generateToken(email));
        }
        return Result.build(ResultStatus.ERROR_SYSTEM, "注册失败！");
    }

    @Override
    public boolean isRegistered(String email) {
        User user = userDao.findFirstByEmail(email);
        return Objects.isNull(user) ? false : true;
    }

    @Override
    public Result login(String email, String password) {
        User user = userDao.findFirstByEmail(email);
        if (Objects.isNull(user)) {
            return Result.build(ResultStatus.ERROR_SYSTEM, "查无此人");
        }
        if (user.getPassword().equalsIgnoreCase(password)) {
            user.setLogintime(new Date());
            userDao.save(user);

            return Result.ok(generateToken(email));
        }
        return Result.build(ResultStatus.ERROR_SYSTEM, "登录失败");
    }

    @Override
    public String getEmailByToken(String tokenText) {
        Token token = tokenDao.findFirstByToken(tokenText);
        return token == null ? "" : token.getEmail();
    }


    private Token generateToken(String email) {
        Token token = new Token();
        token.setEmail(email);
        token.setToken(IdUtil.simpleUUID());
        return tokenDao.save(token);
    }
}
